﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
using DTO.InnerAttribute;

namespace BLL.Util
{
    public class EnumHelper
    {
        /// <summary>
        /// 获取该枚举类型生成简单迭代器
        /// </summary>
        /// <param name="enumType"></param>
        /// <returns></returns>
        public static IEnumerable<KeyValuePair<string, int>> GetEnumEnumerator(Type enumType)
        {
            if (enumType.IsEnum)
            {
                List<KeyValuePair<string, int>> list = new List<KeyValuePair<string, int>>();
                Array ary = Enum.GetValues(enumType);
                for (int i = 0; i < ary.Length; i++)
                {
                    object obj = ary.GetValue(i);
                    int val = (int)obj;
                    string key = obj.ToString();
                    foreach (var myAttributes in enumType.GetField(key).GetCustomAttributes(false))
                    {
                        if (myAttributes is DisplayAttribute)
                        {
                            key = ((DisplayAttribute)myAttributes).DisplayString;
                            break;
                        }
                    }
                    KeyValuePair<string, int> pair = new KeyValuePair<string, int>(key,val);
                    list.Add(pair);
                     
                }
                return list;
            }
            else
            {
                throw new Exception("输入类型错误");
            }
        }
        /// <summary>
        /// 获取枚举显示值，如果没有返回枚举本身名称
        /// </summary>
        /// <param name="enumType"></param>
        /// <returns></returns>
        public static string GetEnumDisplay(Enum enumType)
        {
            var type = enumType.GetType();

            foreach (var myAttributes in type.GetField(enumType.ToString()).GetCustomAttributes(false))
            {
                if (myAttributes is DisplayAttribute)
                {
                    return ((DisplayAttribute)myAttributes).DisplayString;
                }
            }
            return enumType.ToString();
        }


        public static T GetEnumByValue<T>(Type enumType,string value)
        {
            return(T) Enum.Parse(enumType, value);
     
        }
    }
}
